package com.example.dangerouscargodriver.ui.activity;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baiju.bean.CityBean;
import com.baiju.netmanager.Http.IHttpRequest;
import com.baiju.style.citylist.Toast.ToastUtils;
import com.baiju.style.wheelpicker.WheelPickerView;
import com.baiju.style.wheelpicker.bean.WheelItemBean;
import com.baiju.style.wheelpicker.config.WheelPickerConfig;
import com.baiju.style.wheelpicker.listener.OnWheelItemClickListener;
import com.example.dangerouscargodriver.adapter.LineInfoAdapter;
import com.example.dangerouscargodriver.controller.AuthController;
import com.example.dangerouscargodriver.controller.EnterPlatformInfoController;
import com.example.dangerouscargodriver.controller.IControllerEventListener;
import com.example.dangerouscargodriver.entry.CompanyInfo;
import com.example.dangerouscargodriver.entry.CompanyMainInfo;
import com.example.dangerouscargodriver.entry.LineInfo;
import com.example.dangerouscargodriver.entry.LineSearchInfo;
import com.example.dangerouscargodriver.event.Event;
import com.example.dangerouscargodriver.event.LoadHttpResourceStatus;
import com.example.dangerouscargodriver.module.ResponseInfo;
import com.example.dangerouscargodriver.param.RemoteAPI;
import com.example.dangerouscargodriver.param.RemoteAPICmd;
import com.example.dangerouscargodriver.ui.listener.OnLoadMoreListener;
import com.example.dangerouscargodriver.utils.AppManager;
import com.example.dangerouscargodriver.widget.ActionBar;
import com.example.dangerouscargodriver.R;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class CompanyLineListActivity extends HttpRequestActivity implements View.OnClickListener {

    private static final String TAG = "CompanyLineListActivity";
    private static final int MSG_LOAD_ENTER_ATTR_DONE = 0;

    private ActionBar mActionBar = null;
    private Button mAddLine = null;
    private List<LineInfo> mLineInfo = null;
    private RecyclerView mLineRV = null;
    private LineInfoAdapter mAdapter = null;
    private int mOperateId = -1;

    private LinearLayout mCompanySelector = null;
    private WheelPickerView mCompanyPickerView = null;
    private ArrayList<WheelItemBean> mCompanyList = null;
    private WheelItemBean mSelectedBean = null;
    private TextView mCompanyName = null;

    private MyHandler mHandler = null;
    private MyControllerEventListener mIControllerListener = null;

    private int mTotalLineInfoNum = 0;
    private SwipeRefreshLayout mLineLayout = null;
    private OnLoadMoreListener mOnLoadListener = null;

    private TextView mLineNum = null;

    private boolean mCreate = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.initHttpComponent(CompanyListActivity.class);
        setContentView(R.layout.activity_company_line_list);
        AppManager.getAppManager().addActivity(this);
        mHandler = new MyHandler(this);
        mIControllerListener = new MyControllerEventListener();

        mLineInfo = new ArrayList<>();
        mAdapter = new LineInfoAdapter();
        mAdapter.setUserActionListener(new LineInfoAdapter.IUserActionListener() {
            @Override
            public void onEdit(int position) {
                executeEditLineInfo(position);
            }

            @Override
            public void onDelete(int position) {
                executeDeleteLineInfo(position);
            }
        });

        mLineLayout = findViewById(R.id.rv_company_line_layout);
        //设置下拉时圆圈的颜色（可以尤多种颜色拼成）
        mLineLayout.setColorSchemeResources(R.color.base_yellow);
        //设置下拉时圆圈的背景颜色（这里设置成白色）
        mLineLayout.setProgressBackgroundColorSchemeResource(android.R.color.white);

        mLineLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Log.d(TAG, "onRefresh");
                executeSearchLineListAction(true);
            }
        });


        mAddLine = findViewById(R.id.btn_company_add_line);
        mAddLine.setOnClickListener(this);

        mLineRV = findViewById(R.id.rv_company_line_list);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getBaseContext());
        mLineRV.setLayoutManager(layoutManager);
        mLineRV.setAdapter(mAdapter);
        mOnLoadListener = new OnLoadMoreListener() {
            @Override
            protected void onLoading(int countItem, int lastItem) {
                Log.d(TAG, "onLoading");
                executeSearchLineListAction(false);
            }
        };
        mLineRV.addOnScrollListener(mOnLoadListener);
        mLineNum = findViewById(R.id.tv_line_num);

        mCompanySelector = findViewById(R.id.layout_company_belonged_to_selector);
        mCompanySelector.setOnClickListener(this);
        mCompanyPickerView = new WheelPickerView();
        mCompanyList = new ArrayList<WheelItemBean>();
        mCompanyPickerView.init(this, mCompanyList);

        mCompanyName = findViewById(R.id.tv_company_belonged_to);
        mCompanySelector = findViewById(R.id.layout_company_belonged_to_selector);
        mCompanySelector.setOnClickListener(this);

        mActionBar = findViewById(R.id.actionBarCompanyLineList);
        mActionBar.setOnBackClickListener( new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                finish();
            }
        });

        EnterPlatformInfoController.Instance().attachControllerListener(
                CompanyLineListActivity.class,
                mIControllerListener);
    }

    private void executeEditLineInfo(int index){
        if(mOperateId != -1){
            return;
        }
        mOperateId = index;
        Intent intent = new Intent(this, CompanyModifyLineInfoActivity.class);
        CityBean startCityBean = new CityBean();
        startCityBean.setName(mLineInfo.get(mOperateId).getFrom_addr());
        startCityBean.setId(mLineInfo.get(mOperateId).getFrom_id());
        intent.putExtra("start", startCityBean);

        CityBean endCityBean = new CityBean();
        endCityBean.setName(mLineInfo.get(mOperateId).getTo_addr());
        endCityBean.setId(mLineInfo.get(mOperateId).getTo_id());
        intent.putExtra("end", endCityBean);
        intent.putExtra("srid", mLineInfo.get(mOperateId).getId());

        startActivity(intent);
        mOperateId = -1;
    }

    private void executeDeleteLineInfo(int index){
        if(mOperateId != -1){
            return;
        }
        mOperateId = index;
        HashMap<String, String> header = new HashMap<>();
        header.put("token", AuthController.Instance().getToken());

        sendHttpRequest(IHttpRequest.RequestMethod.DELETE_METHOD,
                RemoteAPI.REQUEST_V1_USER_SR + "/" + mLineInfo.get(index).getId(),
                header,
                null,
                RemoteAPICmd.REQUEST_V1_USER_SR_DELETE);
    }

    private void executeSearchLineListAction(boolean refresh){
        HashMap<String, String> header = new HashMap<>();
        header.put("token", AuthController.Instance().getToken());

        HashMap<String, String> param = new HashMap<>();
        param.put("cid", mSelectedBean.getId());

        if(refresh) {
            mTotalLineInfoNum = 0;
            mLineInfo.clear();
            param.put("page", "1");
            sendHttpRequest(IHttpRequest.RequestMethod.GET_METHOD,
                    RemoteAPI.REQUEST_V2_USER_SR,
                    header,
                    param,
                    RemoteAPICmd.REQUEST_V2_USER_SR);
        }
        else{
            if(mLineInfo.size() < mTotalLineInfoNum) {
                param.put("page", String.valueOf(mLineInfo.size() / 20 + 1));
                sendHttpRequest(IHttpRequest.RequestMethod.GET_METHOD,
                        RemoteAPI.REQUEST_V2_USER_SR,
                        header,
                        param,
                        RemoteAPICmd.REQUEST_V2_USER_SR_PAGE);
            }
            else{

            }
        }
    }

    private void initCompanyInfo(){
        List<CompanyInfo> companyInfos =
                EnterPlatformInfoController.Instance().getCompanyInfoList();
        Log.d(TAG, "companyInfos: " + companyInfos.toString());
        if(companyInfos != null && companyInfos.size() > 0){
            mCompanyList.clear();
            for(int index = 0; index < companyInfos.size(); index++) {
                WheelItemBean bean = new WheelItemBean();
                bean.setId(companyInfos.get(index).getCid());
                bean.setName(companyInfos.get(index).getName());

                mCompanyList.add(bean);
            }
            mSelectedBean = mCompanyList.get(0);
        }
    }

    private void showCompanyListSelector(){
        if(mCompanyList.size() <= 0){
            ToastUtils.showLongToast(this, "获取公司信息异常！");
        }
        else{
            WheelPickerConfig pickerConfig = new WheelPickerConfig.Builder()
                    .title("选择类型")
                    .visibleItemsCount(8)
                    .defaultItem(mSelectedBean.getName())
                    .itemCyclic(false)
                    .setCustomItemLayout(R.layout.item_city)//自定义item的布局
                    .setCustomItemTextViewId(R.id.item_city_name_tv)
                    .build();
            pickerConfig.setTitleBackgroundColorStr("#FFD401");

            mCompanyPickerView.setConfig(pickerConfig);
            mCompanyPickerView.setOnItemClickListener(new OnWheelItemClickListener() {
                @Override
                public void onSelected(WheelItemBean type) {
                    if(type != null){
                        if(!mSelectedBean.getId().equals(type.getId())){
                            mSelectedBean = type;
                            mLineInfo.clear();
                            mAdapter.clearData();
                            executeSearchLineListAction(true);
                        }
                        else{
                            mSelectedBean = type;
                        }
                        refreshCompanySelectInfo();
                    }
                }

                @Override
                public void onCancel() {
                    /**/
                }
            });
            mCompanyPickerView.showWheelPicker();
        }
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.btn_company_add_line){
            Intent intent = new Intent(this, CompanyAddLineInfoActivity.class);
            startActivity(intent);
        }
        else if(v.getId() == R.id.layout_company_belonged_to_selector){
            showCompanyListSelector();
        }
        else{

        }
    }

    private void refreshCompanyLineListView() {
        mAdapter.clearData();
        mAdapter.appendData(mLineInfo);
        mAdapter.notifyDataSetChanged();
    }

    private void refreshCompanySelectInfo(){
        mCompanyName.setText(mSelectedBean.getName());
    }

    @Override
    protected void onHttpResponse(int actionId, String response) {
        try {
            JSONObject res = new JSONObject(response);
            Gson gson = new Gson();
            if(actionId == RemoteAPICmd.REQUEST_V2_USER_SR) {
                Log.d(TAG, "onResponse: " + response);
                ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
                if(responseInfo != null && responseInfo.getStatus() == 1){
                    LineSearchInfo searchInfo = gson.fromJson(res.getJSONObject("data").toString(),
                            LineSearchInfo.class);
                    if(searchInfo.getCount() > 0){
                        mTotalLineInfoNum = searchInfo.getCount();
                        mLineNum.setText(String.valueOf(mTotalLineInfoNum) + "/100");
                        mLineInfo = searchInfo.getList();
                        refreshCompanyLineListView();
                    }
                }
                mLineLayout.setRefreshing(false);
            }
            else if(actionId == RemoteAPICmd.REQUEST_V2_USER_SR_PAGE) {
                Log.d(TAG, "onResponse: " + response);
                ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
                if(responseInfo != null && responseInfo.getStatus() == 1){
                    LineSearchInfo searchInfo = gson.fromJson(res.getJSONObject("data").toString(),
                            LineSearchInfo.class);
                    Log.d(TAG, "mLineInfo.size: " + mLineInfo.size());
                    if(searchInfo.getCount() > 0){
                        List<LineInfo> lineInfos = searchInfo.getList();
                        for(int index = 0; index < lineInfos.size(); index++){
                            mLineInfo.add(lineInfos.get(index));
                        }

                        refreshCompanyLineListView();
                    }
                }
            }
            else if(actionId == RemoteAPICmd.REQUEST_V1_USER_SR_DELETE){
                Log.d(TAG, "onResponse: " + response);
                ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
                if(responseInfo != null && responseInfo.getStatus() == 1){
                    if(mOperateId != -1) {
                        mAdapter.removeData(mOperateId);
                        mLineInfo.remove(mOperateId);
                    }
                    else{
                        /**/
                    }
                }
                else{

                }
                mOperateId = -1;
            }
            else{
                /**/
            }
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onHttpErrorResponse(int actionId, String response) {
        if(actionId == RemoteAPICmd.REQUEST_V2_USER_SR) {
            mLineLayout.setRefreshing(false);
        }
        else if(actionId == RemoteAPICmd.REQUEST_V1_USER_SR_DELETE){
            mOperateId = -1;
        }
        else{

        }
    }

    @Override
    public void onResume(){
        super.onResume();
        if(!mCreate) {
            executeSearchLineListAction(true);
        }
        else{
            mCreate = false;
        }
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        Log.d(TAG, "onDestroy");
        EnterPlatformInfoController.Instance().unAttachControllerListener(
                CompanyLineListActivity.class,
                mIControllerListener);
        mCompanyList = null;
        mCompanyPickerView = null;
        mHandler = null;
        mIControllerListener = null;
    }

    private class MyHandler extends Handler {
        WeakReference<CompanyLineListActivity> mActivity;

        MyHandler(CompanyLineListActivity activity) {
            mActivity = new WeakReference<CompanyLineListActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            CompanyLineListActivity activity = mActivity.get();
            switch (msg.what){
                case MSG_LOAD_ENTER_ATTR_DONE:
                    activity.initCompanyInfo();
                    activity.refreshCompanySelectInfo();
                    activity.executeSearchLineListAction(true);
                    break;
            }
        }
    }

    private class MyControllerEventListener implements IControllerEventListener {

        @Override
        public void onEvent(int eventId, String json) {
            if(eventId == Event.EVENT_LOAD_HTTP_ENTER_STATUS){
                Gson gson = new Gson();
                LoadHttpResourceStatus status = gson.fromJson(json, LoadHttpResourceStatus.class);
                Log.d(TAG, "onEvent: " + status.toJson());
                if(status.getWhat() == EnterPlatformInfoController.LOAD_ENTER_STATUS_DONE){
                    Message msg = new Message();
                    msg.what = MSG_LOAD_ENTER_ATTR_DONE;
                    mHandler.sendMessage(msg);
                }
            }
        }
    }
}